package com.fy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fy.ex.ConditionException;
import com.fy.mapper.AnnouCheckMapper;
import com.fy.mapper.AnnouncementMapper;
import com.fy.pojo.entity.AnnouCheck;
import com.fy.pojo.entity.Announcement;
import com.fy.pojo.vo.announcement.UserAnnouncementVO;
import com.fy.service.AnnouCheckService;
import com.fy.utils.DateFormatter;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author fwq
 * @description 针对表【annou_check】的数据库操作Service实现
 * @createDate 2025-01-10 15:02:57
 */
@Service
public class AnnouCheckServiceImpl extends ServiceImpl<AnnouCheckMapper, AnnouCheck> implements AnnouCheckService {

    @Autowired
    private AnnouCheckMapper annouCheckMapper;

    @Autowired
    private AnnouncementMapper announcementMapper;

    /**
     * 查看公告
     *
     * @param userId
     * @param annouId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserAnnouncementVO readAnnouncement(Long userId, Long annouId) {
        // 1. 查询公告
        Announcement announcement = announcementMapper.selectById(annouId);
        if (announcement == null) {
            throw new ConditionException("公告不存在");
        }

        // 2. 检查是否已读
        LambdaQueryWrapper<AnnouCheck> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AnnouCheck::getUserId, userId)
                .eq(AnnouCheck::getAnnouId, annouId);
        Long count = annouCheckMapper.selectCount(wrapper);

        // 3. 如果未读，添加已读记录
        if (count == 0) {
            AnnouCheck annouCheck = new AnnouCheck();
            annouCheck.setUserId(userId);
            annouCheck.setAnnouId(annouId);
            annouCheckMapper.insert(annouCheck);
        }

        // 4. 转换并返回公告信息
        UserAnnouncementVO vo = new UserAnnouncementVO();
        BeanUtils.copyProperties(announcement, vo);
        vo.setShowTime(DateFormatter.getTimestampStringByDate(announcement.getShowTime()));
        vo.setReadStatus(1); // 设置为已读

        return vo;
    }
}
